package com.easipass.framework.eirframeworkcoredsl.graph;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_EMPTY)
public class Node {

    public static final String METADATA_LABEL = "label";
    public static final String START = "start";
    public static final String END = "end";
    public static final String FREEMOD = "freedom";

    public String id;

    public String name;

    public String type;

    public String primaryKey;

    public Map<String, String> properties;

    public Map<String, String> metadata;

    Node() {
    }

    public Node(String id, String name, String type, String primaryKey) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.properties = null;
        this.primaryKey = primaryKey;
    }

    public Node(String id, String name, String type) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.properties = null;
        this.primaryKey = generatedPrimaryKey();
    }

    public Node(String id, String name, String type, Map<String, String> properties) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.properties = properties;
        this.primaryKey = generatedPrimaryKey();
    }

    public String generatedPrimaryKey() {
        return generatedPrimaryKey(this.type);
    }

    public String generatedPrimaryKey(String type) {
        return type + "-" + UUID.randomUUID();
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append("Node[id=").append(id).append(",name=").append(name);
        if (properties != null) {
            s.append(",properties=").append(properties);
        }
        s.append("]");
        return s.toString();
    }

    @JsonIgnore
    public boolean isStart() {
        return type.equals("START");
    }

    @JsonIgnore
    public boolean isEnd() {
        return name.equals("END");
    }

    @JsonIgnore
    public boolean isFail() {
        return name.equals("FAIL");
    }

    @JsonIgnore
    public boolean isSync() {
        return name.equals("SYNC");
    }

    @JsonIgnore
    public String getLabel() {
        if (metadata == null) {
            return null;
        } else {
            return metadata.get(METADATA_LABEL);
        }
    }

    @JsonIgnore
    public void setLabel(String label) {
        if (metadata == null) {
            metadata = new HashMap<>();
        }
        metadata.put(METADATA_LABEL, label);
    }
}
